package org.summer.manager.nacos;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import jakarta.annotation.PostConstruct;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.Properties;
import java.util.concurrent.Executor;


/**
 * @author gvp9132
 * @date 2024/9/23
 * @since 1.0
 */
@Log4j2
//@Component
public class NacosDynamicConfig implements ApplicationRunner {
    private final ApplicationEventPublisher publisher;

    private ConfigService configService;

//    @Autowired
    public NacosDynamicConfig(ApplicationEventPublisher publisher, NacosConfigProperties nacosConfigProperties) throws NacosException {
        this.publisher = publisher;
        Properties properties = new Properties();
        properties.setProperty("serverAddr", nacosConfigProperties.getServerAddr());
        properties.setProperty("namespace", nacosConfigProperties.getNamespace());
        properties.setProperty("username", nacosConfigProperties.getUsername());
        properties.setProperty("password", nacosConfigProperties.getPassword());
        this.configService = NacosFactory.createConfigService(properties);
    }


    @Override
    public void run(ApplicationArguments args) throws NacosException {
        log.info("从nacos配置中读取jsonConfig: {}",configService);
            var jsonConfig = this.configService.getConfig("test-config.json", "GVP_TEST_GROUP", 3000);
            log.debug("从nacos配置中读取jsonConfig: {}", jsonConfig);
            configService.addListener("test-config.json", "GVP_TEST_GROUP", new Listener() {
                @Override
                public Executor getExecutor() {
                    log.debug("-----------------------");
                    return null;
                }
                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.debug("刷新的jsonConfig: {}", configInfo);
                }
            });
    }

}
